package com.xwdeshj.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class helper {
	/**
	 * 获取某个cookie
	 * @param request
	 * @return
	 */
	public static Object ReadCookieMap(HttpServletRequest request, String key){
	    Cookie[] cookies = request.getCookies();
	    String value="";
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	        	if(key.equals(cookie.getName())){
	        		value=cookie.getValue();
	        	}
	        }
	    }
		return value;
	}
	/**
	 * 获取所有cookie
	 * @param request
	 * @return
	 */
	public static Map<String,Object> ReadCookieMap(HttpServletRequest request){
	    Map<String,Object> cookieMap = new HashMap<String,Object>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie.getValue());
	        }
	    }
	    return cookieMap;
	}
	/**
	 * 删除登录的cookie
	 * @param response
	 */
	public static void DelLoginCookie(HttpServletResponse response, HttpServletRequest request) {
        Cookie datacookie = new Cookie("admin_datacookie", "");
        datacookie.setMaxAge(0);
		response.addCookie(datacookie);
		datacookie.setPath("/");
		Cookie lastcookie = new Cookie("admin_lastcookie", "");
		lastcookie.setMaxAge(0);
		lastcookie.setPath("/");
		response.addCookie(lastcookie);
		System.out.println("delete cookie");
    }
	/**
	 * 获取用户IP
	 */
	public static String getRemortIP(HttpServletRequest request) {
	    if (request.getHeader("x-forwarded-for") == null) {  
	        return request.getRemoteAddr();  
	    }  
	    return request.getHeader("x-forwarded-for");  
	}  
	public static boolean checkjson(String json) {
	 if(json.indexOf("请重新登录")>-1){
		 return false;
	 }else{
		 return true;
	 }
	}  
	public static String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}
}
